<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/**
 * @author Anh Nguyen <duyanhnguyen@vccorp.vn>
 * @copyright 2012
 */
class Variation extends MX_Controller
{

    function __construct()
    {
        parent::__construct();
        $this->load->library('Admin_Layout');
        $this->load->model('sim/sim_model');
        $this->load->model('network/network_model');
        $this->load->model('group/group_model');
        $this->load->model('city/city_model');
        $this->load->library('pagination');
        $this->load->helper('url');
        $this->load->library('table');
    }

    public function add()
    {
        $this->mycommon->authAdmin();
        $data = array();
        $data['error'] = '';
        $this->load->library('Form_validation');
        $this->load->library('Minifier');
        $this->minifier->AddJsNoPack('jquery.meio.mask');
        $this->load->model('network/network_model');
        $this->load->model('group/group_model');
        $this->load->model('city/city_model');
        $this->form_validation->CI = & $this;
        $data['current'] = 1;
        $this->form_validation->set_error_delimiters('<li>', '</li>');
        $data['listNetwork'] = $this->network_model->getFullNetwork();
        $data['listCity'] = $this->city_model->getFullCity();
        $data['listGroup'] = $this->group_model->getFullGroup();
        if ($this->input->post('submit') && $this->input->post('frmToken') && $this->session->userdata('frmToken') && $this->input->post('frmToken') == $this->session->userdata('frmToken')) {
            $this->form_validation->set_rules('phone', 'Số điện thoại', 'required|min_length[3]');
            $this->form_validation->set_rules('network', 'Nhà cung cấp', 'required');
            $this->form_validation->set_rules('price', 'Giá tiền', 'required');
            $this->form_validation->set_message('required', '%s không được để trống');
            $this->form_validation->set_message('min_length', '%s ít nhất %d ký tự');
            if ($this->form_validation->run() == TRUE) {
                $phone = $this->input->post('phone', TRUE);
                $network = $this->input->post('network', TRUE);
                $city = $this->input->post('city', TRUE);
                $group = $this->input->post('group', TRUE);
                $price = $this->input->post('price', TRUE);
                $time = time();
                $network = intval($network);
                $city = intval($city);
                $group = intval($group);
                $price = intval(str_replace(',', '', $price));
                if ($phone != '' && $network != 0 && $price != '') {
                    if(! $this->sim_model->checkExists($phone)){
                    if ($this->sim_model->addSim($phone, $network, $city, $group, $price, $time)) {
                        redirect('admin/variation');
                    }
                } else {
                    $data['error'] = 'Số sim đã có, xin vui lòng thực hiện lại';
                }
                } else {
                    $data['error'] = 'Thông tin nhập vào chưa chính xác';
                }
            }
        }
        $data['frmToken'] = uniqid();
        $data['headTitle'] = 'Thêm số điện thoại';
        $this->session->set_userdata('frmToken', $data['frmToken']);
        $this->admin_layout->render('sim/add_sim_view', $data);
    }
    
    public function actionSelected()
    {
        $this->mycommon->authAdmin();
        $actionSlc = $this->input->post('actionSlc', TRUE);
        $variation = $this->input->post('variation', TRUE);
        $slcValid = array(
            'delete',
            'hide',
            'show'
        );
        $data = array();
        if(in_array($actionSlc, $slcValid) && is_array($variation) && count($variation) != 0) {
            if($actionSlc == 'show') {
                $data = array(
                    'delete_flag' => '0'
                );
                $this->sim_model->updateSimArray($variation, $data);
            } elseif( $actionSlc == 'hide') {
                $data = array(
                    'delete_flag' => '1'
                );
                $this->sim_model->updateSimArray($variation, $data);
            } elseif($actionSlc == 'delete') {
                $this->sim_model->deleteSimArray($variation);
            }
        }
        $arr = $this->session->flashdata('filterVariation');
        if($arr) {
            $this->session->keep_flashdata('filterVariation');
        }
        $this->session->set_flashdata('variation_msg', 'Cập nhật thành công!');
        $suffix = "";
        $arrFlashdata = $this->session->flashdata('filterVariation');
        if($arrFlashdata) {
            $arrFlashdata = json_decode($arrFlashdata);
            $suffix = "/{$arrFlashdata->page}.html?k={$arrFlashdata->keyword}&s={$arrFlashdata->filterStatus}&o={$arrFlashdata->filterOrdered}&g={$arrFlashdata->filterGroup}&n={$arrFlashdata->filterNetwork}&a={$arrFlashdata->filterAgent}&num={$arrFlashdata->number}";
        }
        redirect(base_url('admin/variation/index' . $suffix));
    }

    public function checkUrl($url)
    {
        if ($this->mycommon->isUrl($url)) {
            return true;
        }
        return false;
    }

    public function index($page = '')
    {
        $this->mycommon->authAdmin();
        $data = array();
        $page = ($page != '') ? intval($page) : 1;
        $keyword = $this->input->get('k', TRUE);
        $filterStatus = $this->input->get('s', TRUE);
        $filterStatus = ($filterStatus!= '' && in_array($filterStatus, array(1,0))) ? $filterStatus : '';
        $filterOrdered = $this->input->get('o', TRUE);
        $filterOrdered = ($filterOrdered != '' && in_array($filterOrdered, array(1,0))) ? $filterOrdered : '';
        $filterGroup = $this->input->get('g', TRUE);
        $filterGroup = ($filterGroup != '') ? intval($filterGroup) : '';
        $filterNetwork = $this->input->get('n', TRUE);
        $filterNetwork = ($filterNetwork != '') ? intval($filterNetwork) : '';
        $filterAgent = $this->input->get('a', TRUE);
        $filterAgent = ($filterAgent != '') ? intval($filterAgent) : '';
        
        $arrFlashdata = array(
            'page'      =>  $page,
            'keyword'   =>  $keyword,
            'filterStatus'  =>  $filterStatus,
            'filterOrdered' =>  $filterOrdered,
            'filterGroup'   =>  $filterGroup,
            'filterNetwork' =>  $filterNetwork,
            'filterAgent'   =>  $filterAgent
        );
        $numPost = $this->sim_model->count_all($keyword, $filterStatus, $filterOrdered);
        $number = $this->input->get('num', TRUE);
        $number = ($number != '' && intval($number) != 0) ? intval($number) : 50;
        $arrFlashdata['number'] = $number;
        $this->session->set_flashdata('filterVariation', json_encode($arrFlashdata));
        $config['base_url'] = '/admin/variation/index';
        $config['total_rows'] = $numPost;
        $config['per_page'] = $number;
        $config['use_page_numbers'] = TRUE;
        $config['first_link'] = '«';
        $config['last_link'] = '»';
        $config['cur_tag_open'] = '<a href="#" class="active">';
        $config['cur_tag_close'] = '</a>';
        $config['num_links'] = '6';
        $config['cur_page'] = $page;
        $config['uri_segment'] = 3;
        $config["suffix"] = ".html?k=$keyword&s=$filterStatus&o=$filterOrdered&g=$filterGroup&n=$filterNetwork&a=$filterAgent&num=$number";
        $this->pagination->initialize($config);
        $start = ($page - 1) * $config['per_page'];
        $data['pagination'] = $this->pagination->create_links();
        $data['headTitle'] = 'Quản lý sim';
        $data['current'] = 1;
        $data['keyword'] = $keyword;
        $data['status'] = $filterStatus;
        $data['order'] = $filterOrdered;
        $data['fGroup'] = $filterGroup;
        $data['fNetwork'] = $filterNetwork;
        $data['fAgent'] = $filterAgent;
        $data['curpage'] = $page;
        $data['number'] = $number;
        $this->load->library('Minifier');
        $this->load->model('group/group_model');
        $this->load->model('city/city_model');
        $this->load->model('network/network_model');
        $data['sim'] = $this->sim_model->getAllSim($config['per_page'],$start,$keyword, $filterStatus, $filterOrdered, $filterGroup, $filterNetwork, $filterAgent);
        $data['group'] = $this->group_model->getFullGroup();
        $data['city'] = $this->city_model->getFullCity();
        $data['network'] = $this->network_model->getFullNetwork();
        $this->admin_layout->render('sim/sim_view', $data);
    }
    
    public function export()
    {
        set_time_limit(0);
        $this->mycommon->authAdmin();
        $data = array();
        $keyword = $this->input->get('k', TRUE);
        $page = $this->input->get('page', TRUE);
        $page = ($page != '') ? intval($page) : 1;
        $number = $this->input->get('num', TRUE);
        $number = ($number != '' && intval($number) != 0) ? intval($number) : 50;
        $start = ($page - 1) * $number;
        $filterStatus = $this->input->get('s', TRUE);
        $filterStatus = ($filterStatus!= '' && in_array($filterStatus, array(1,0))) ? $filterStatus : '';
        $filterOrdered = $this->input->get('o', TRUE);
        $filterOrdered = ($filterOrdered != '' && in_array($filterOrdered, array(1,0))) ? $filterOrdered : '';
        $filterGroup = $this->input->get('g', TRUE);
        $filterGroup = ($filterGroup != '') ? intval($filterGroup) : '';
        $filterNetwork = $this->input->get('n', TRUE);
        $filterNetwork = ($filterNetwork != '') ? intval($filterNetwork) : '';
        $filterAgent = $this->input->get('a', TRUE);
        $filterAgent = ($filterAgent != '') ? intval($filterAgent) : '';
        $numPost = $this->sim_model->count_all($keyword, $filterStatus, $filterOrdered);
        $data['keyword'] = $keyword;
        $data['status'] = $filterStatus;
        $data['order'] = $filterOrdered;
        $this->load->library('Minifier');
        $data['sim'] = $this->sim_model->getAllSim($number,$start,$keyword, $filterStatus, $filterOrdered, $filterGroup, $filterNetwork, $filterAgent);
        $this->admin_layout->render('sim/export_view', $data);
    }

    public function hide($Id = '')
    {
        $this->mycommon->authAdmin();
        if ($Id == '') {
            show_404();
        }
        $data = array(
            'delete_flag' => '1'
        );
        $this->sim_model->updateSimDeleteF($Id, $data);
        $suffix = "";
        $arrFlashdata = $this->session->flashdata('filterVariation');
        if($arrFlashdata) {
            $arrFlashdata = json_decode($arrFlashdata);
            $suffix = "/{$arrFlashdata->page}.html?k={$arrFlashdata->keyword}&s={$arrFlashdata->filterStatus}&o={$arrFlashdata->filterOrdered}&g={$arrFlashdata->filterGroup}&n={$arrFlashdata->filterNetwork}&a={$arrFlashdata->filterAgent}&num={$arrFlashdata->number}";
        }
        redirect(base_url('admin/variation/index' . $suffix));
    }
    
    public function show($Id = '')
    {
        $this->mycommon->authAdmin();
        if ($Id == '' && intval($Id) != 0) {
            show_404();
        }
        $Id = intval($Id);
        $data = array(
            'delete_flag' => '0'
        );
        $this->sim_model->updateSimDeleteF($Id, $data);
        $suffix = "";
        $arrFlashdata = $this->session->flashdata('filterVariation');
        if($arrFlashdata) {
            $arrFlashdata = json_decode($arrFlashdata);
            $suffix = "/{$arrFlashdata->page}.html?k={$arrFlashdata->keyword}&s={$arrFlashdata->filterStatus}&o={$arrFlashdata->filterOrdered}&g={$arrFlashdata->filterGroup}&n={$arrFlashdata->filterNetwork}&a={$arrFlashdata->filterAgent}&num={$arrFlashdata->number}";
        }
        redirect(base_url('admin/variation/index' . $suffix));
    }
    
    public function Sale($Id = '')
    {
        $this->mycommon->authAdmin();
        $arr = $this->session->flashdata('filterVariation');
        if($arr) {
            $this->session->keep_flashdata('filterVariation');
        }
        if ($Id == '') {
            show_404();
        }
        $data = array(
            'status' => '1'
        );
        $this->sim_model->updateSimDeleteF($Id, $data);
        $suffix = "";
        $arrFlashdata = $this->session->flashdata('filterVariation');
        if($arrFlashdata) {
            $arrFlashdata = json_decode($arrFlashdata);
            $suffix = "/{$arrFlashdata->page}.html?k={$arrFlashdata->keyword}&s={$arrFlashdata->filterStatus}&o={$arrFlashdata->filterOrdered}&g={$arrFlashdata->filterGroup}&n={$arrFlashdata->filterNetwork}&a={$arrFlashdata->filterAgent}&num={$arrFlashdata->number}";
        }
        redirect(base_url('admin/variation/index' . $suffix));
    }
    
    public function StatusNew($Id = '')
    {
        $this->mycommon->authAdmin();
        $arr = $this->session->flashdata('filterVariation');
        if($arr) {
            $this->session->keep_flashdata('filterVariation');
        }
        if ($Id == '') {
            show_404();
        }
        $data = array(
            'status' => '0'
        );
        $this->sim_model->updateSimDeleteF($Id, $data);
        $suffix = "";
        $arrFlashdata = $this->session->flashdata('filterVariation');
        if($arrFlashdata) {
            $arrFlashdata = json_decode($arrFlashdata);
            $suffix = "/{$arrFlashdata->page}.html?k={$arrFlashdata->keyword}&s={$arrFlashdata->filterStatus}&o={$arrFlashdata->filterOrdered}&g={$arrFlashdata->filterGroup}&n={$arrFlashdata->filterNetwork}&a={$arrFlashdata->filterAgent}&num={$arrFlashdata->number}";
        }
        redirect(base_url('admin/variation/index' . $suffix));
    }

    public function delete($Id = '')
    {
        $this->mycommon->authAdmin();
        $arr = $this->session->flashdata('filterVariation');
        if($arr) {
            $this->session->keep_flashdata('filterVariation');
        }
        if ($Id == '' && intval($Id) != 0) {
            show_404();
        }
        $Id = intval($Id);
        $this->sim_model->deleteSim($Id);
        $suffix = "";
        $arrFlashdata = $this->session->flashdata('filterVariation');
        if($arrFlashdata) {
            $arrFlashdata = json_decode($arrFlashdata);
            $suffix = "/{$arrFlashdata->page}.html?k={$arrFlashdata->keyword}&s={$arrFlashdata->filterStatus}&o={$arrFlashdata->filterOrdered}&g={$arrFlashdata->filterGroup}&n={$arrFlashdata->filterNetwork}&a={$arrFlashdata->filterAgent}&num={$arrFlashdata->number}";
        }
        redirect(base_url('admin/variation/index' . $suffix));
    }

    public function edit($Id = '')
    {
        $this->mycommon->authAdmin();
        if ($Id == '' && intval($Id) != 0) {
            show_404();
        }
        $Id = intval($Id);
        $data = array();
        $data['all'] = $this->sim_model->getInfo($Id);
        if(!isset($data['all'][0]))
            show_404();
        $data['error'] = '';
        $this->load->library('Form_validation');
        $this->load->library('Minifier');
        $this->minifier->AddJsNoPack('jquery.meio.mask');
        $this->load->model('network/network_model');
        $this->load->model('group/group_model');
        $this->load->model('city/city_model');
        $this->form_validation->CI = & $this;
        $this->form_validation->set_error_delimiters('<li>', '</li>');
        $data['current'] = 1;
        $data['listNetwork'] = $this->network_model->getFullNetwork();
        $data['listCity'] = $this->city_model->getFullCity();
        $data['listGroup'] = $this->group_model->getFullGroup();
        if ($this->input->post('submit') && $this->input->post('frmToken') && $this->session->userdata('frmToken') && $this->input->post('frmToken') == $this->session->userdata('frmToken')) {
            $this->form_validation->set_rules('phone', 'Số điện thoại', 'required|min_length[3]');
            $this->form_validation->set_rules('network', 'Nhà cung cấp', 'required');
            $this->form_validation->set_rules('price', 'Giá tiền', 'required');
            $this->form_validation->set_message('required', '%s không được để trống');
            $this->form_validation->set_message('min_length', '%s ít nhất %d ký tự');
            if ($this->form_validation->run() == TRUE) {
                $phone = $this->input->post('phone', TRUE);
                $network = $this->input->post('network', TRUE);
                $city = $this->input->post('city', TRUE);
                $group = $this->input->post('group', TRUE);
                $price = $this->input->post('price', TRUE);
                $network = intval($network);
                $city = intval($city);
                $group = intval($group);
                $price = intval(str_replace(',', '', $price));
                $array = array(
                    'phone'=>$phone,
                    'list_network_id'=>$network,
                    'list_city_id'=>$city,
                    'list_group_id'=>$group,
                    'price_update'=>$price
                );
                if ($phone != '' && $network != 0 && $price != '') {
                    if ($this->sim_model->updateSim($Id,$array)) {
                        redirect('admin/variation/index');
                    }
                } else {
                    $data['error'] = 'Thông tin nhập vào chưa chính xác';
                }
            }
        }
        $data['frmToken'] = uniqid();
        $data['headTitle'] = 'Sửa thông tin';
        $this->session->set_userdata('frmToken', $data['frmToken']);
        $this->admin_layout->render('sim/edit_sim_view', $data);
    }
    
    public function import()
    {
        $this->mycommon->authAdmin();
        $data = array();
        $data['current'] = 1;
        $data['headTitle'] = 'Import from Excel document';
        $this->load->library('Minifier');
        $this->minifier->AddCss('uploadify');
        $this->minifier->AddJsNoPack('uploadify/jquery.uploadify.min');
        $this->admin_layout->render('sim/import_view', $data);
    }
    
    public function upload()
    {
        $targetFolder = '/uploads/files';
        $res = array();
        $res['error'] = '';

        if (!empty($_FILES)) {
            $tempFile = $_FILES['Filedata']['tmp_name'];
            $fileName = $_FILES['Filedata']['name'];
            $targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;
            $fileName = explode('.', $fileName);
            $fileName[0] = $fileName[0] . '_' .  uniqid();
            $fileName = implode('.', $fileName);
            // Validate the file type
            $fileTypes = array('xls','xlsx'); // File extensions
            $targetFile = rtrim($targetPath,'/') . '/' . $fileName;
            $fileParts = pathinfo($_FILES['Filedata']['name']);
            if (in_array($fileParts['extension'],$fileTypes)) {
                move_uploaded_file($tempFile,$targetFile);
                $res['filename'] = $fileName;
            } else {
                $res['error'] = "File upload không hợp lệ";
            }
        } else {
            $res['error'] = 'Có lỗi xảy ra, vui lòng thực hiện lại';
        }
        echo json_encode($res);
    }
    
    public function importAjax()
    {
        $this->mycommon->authAdmin();
        $fileName = $this->input->get('fileName', TRUE);
        $fieldNetwork = $this->input->get('fieldNetwork', TRUE);
        $fieldGroup = $this->input->get('fieldGroup', TRUE);
        $fieldAgent = $this->input->get('fieldAgent', TRUE);
        $fieldPrice = $this->input->get('fieldPrice', TRUE);
        $fieldSim = $this->input->get('fieldSim', TRUE);
        $prefixNetwork = $this->input->get('prefixNetwork', TRUE);
        $prefixGroup = $this->input->get('prefixGroup', TRUE);
        $prefixAgent = $this->input->get('prefixAgent', TRUE);
        //-- Read file excel
        include_once APPPATH . "libraries/PHPExcel/PHPExcel/IOFactory.php";
        $uploadPath = FCPATH . "uploads/files/";
        $inputFile = $uploadPath . $fileName;
        $objPHPExcel = PHPExcel_IOFactory::load($inputFile);
        $sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,false);
        @unlink($inputFile);
        array_shift($sheetData);
        //$allSim = $this->sim_model->getInfoItemsim();
        //$allinfo[0] = $allSim;
        
        $allListCity = $this->sim_model->getInfoListCity();
        $allinfo[1] = $allListCity;
        
        $allListGroup = $this->sim_model->getInfoListGroup();
        $allinfo[2] = $allListGroup;
        
        $allListNetwork = $this->sim_model->getInfoListNetwoork();
        $allinfo[3] = $allListNetwork;
        //$allinfo = $this->sim_model->getAllInfo();
        
        $itemValid = array();
        $simValid = array();
        $groupValid = array();
        $networkValid = array();
        $agentValid = array();
        //-- Duyệt theo nhóm, lấy nhóm chưa tồn tại
        foreach($sheetData as $kg => $vg) {
            $tmpName = str_replace($prefixGroup, '', $vg[$fieldGroup]);
            $tmpName = preg_replace('/\s+/', ' ', $tmpName);
            $tmpName = trim($tmpName);
            $exists = false;
            foreach($allinfo['2'] as $_kg => $_vg) {
                if(trim(preg_replace('/\s+/','',strtolower($tmpName))) == trim(preg_replace('/\s+/','',strtolower($_vg['name'])))){
                    $exists = true;
                    break;
                }
            }
            if(!$exists && !in_array($tmpName, $groupValid) && $tmpName != '') {
                array_push($groupValid, $tmpName);
            }
        }
        //-- END
        //-- Duyệt theo nhà mạng

        foreach($sheetData as $kn => $vn) {
            $tmpName = str_replace($prefixNetwork, '', $vn[$fieldNetwork]);
            $tmpName = preg_replace('/\s+/', '', $tmpName);
            $tmpName = trim($tmpName);
            $exists = false;
            foreach($allinfo['3'] as $_kn => $_vn) {
                if(trim(preg_replace('/\s+/','',strtolower($tmpName))) == trim(preg_replace('/\s+/','',strtolower($_vn['name'])))){
                    $exists = true;
                    break;
                }
            }
            if(!$exists && !in_array($tmpName, $networkValid) && $tmpName != '') {
                array_push($networkValid, $tmpName);
            }
        }
        //--End
        //-- Duyệt theo đại lý
        foreach($sheetData as $ka => $va) {
            $tmpName = str_replace($prefixAgent, '', $va[$fieldAgent]);
            $tmpName = preg_replace('/\s+/', ' ', $tmpName);
            $tmpName = trim($tmpName);
            $exists = false;
            foreach($allinfo['1'] as $_ka => $_va) {
                if(trim(preg_replace('/\s+/','',strtolower($tmpName))) == trim(preg_replace('/\s+/','',strtolower($_va['name'])))){
                    $exists = true;
                    break;
                }
            }
            if(!$exists && !in_array($tmpName, $agentValid) && $tmpName != '') {
                array_push($agentValid, $tmpName);
            }
        }
        //--End
        //- Duyệt theo sim, giá
        foreach($sheetData as $ks => $vs) {
            $price = $vs[$fieldPrice];
            $simNumber = $vs[$fieldSim];
            $groupName = $vs[$fieldGroup];
            $networkName = $vs[$fieldNetwork];
            $agentName = $vs[$fieldAgent];
            $groupName = preg_replace('/\s+/', ' ', $groupName);
            $groupName = trim($groupName);
            $networkName = preg_replace('/\s+/', ' ', $networkName);
            $networkName = trim($networkName);
            $agentName = preg_replace('/\s+/', ' ', $agentName);
            $groupName = trim($groupName);
            $networkName = trim($networkName);
            $agentName = trim($agentName);
            $simNumber = preg_replace('/[^\d+]/', ' ', $simNumber);
            $price = preg_replace('/[^\d+]/', ' ', $price);
            $price = preg_replace('/\s/', '', $price);
//            $exists = false;
//            foreach($allinfo['0'] as $_ks => $_vs) {
//                if(strtolower($simNumber) == strtolower($_vs['phone'])){
//                    $exists = true;
//                    break;
//                }
//            }
//            if(!$exists && !in_array($simNumber, $simValid) && $simNumber !='') {
                array_push($simValid, $simNumber);
                array_push($itemValid, array(
                    'sim'   =>  $simNumber,
                    'price' =>  $price,
                    'group' =>  $groupName,
                    'network'=> $networkName,
                    'agent'     =>  $agentName
                ));
//            } 
        }
        //-- End sim
        //-- Insert to db
        
        ///////Insert group
        $batchGroup = array();
        foreach($groupValid as $gk => $gv) {
            array_push($batchGroup, array(
                'name'  =>  $gv,
                'delete_flag'  =>   '0'
            ));
        }
        
        if(count($batchGroup) != 0)
            $this->group_model->addGroupBatch($batchGroup);
        //////END
        ///////Insert Network
        $batchNetwork = array();
        foreach($networkValid as $nk => $nv) {
            array_push($batchNetwork, array(
                'name'  =>  $nv,
                'delete_flag'  =>   '0'
            ));
        }
        if(count($batchNetwork) != 0)
            $this->network_model->addNetworkBatch($batchNetwork);
        //////END
        ///////Insert agent
        $batchAgent = array();
        foreach($agentValid as $ak => $av) {
            array_push($batchAgent, array(
                'name'  =>  $av,
                'delete_flag'  =>   '0'
            ));
        }
        if(count($batchNetwork) != 0)
            $this->city_model->addAgentBatch($batchAgent);
        //////END
        ///////Insert sim
        $simBatch = array();
        //$allSim = $this->sim_model->getInfoItemsim();
        //$allinfo[0] = $allSim;
        
        $allListCity = $this->sim_model->getInfoListCity();
        $allinfo[1] = $allListCity;
        
        $allListGroup = $this->sim_model->getInfoListGroup();
        $allinfo[2] = $allListGroup;
        
        $allListNetwork = $this->sim_model->getInfoListNetwoork();
        $allinfo[3] = $allListNetwork;
//        $allinfo = $this->sim_model->getAllInfo();
        
        $time = time();
        foreach ($itemValid as $_ik => $_iv){
            $_iv['group_id'] = '';
            $_iv['network_id'] = '';
            $_iv['agent_id'] = '';
            //-- Invert group name to id
            
            foreach($allinfo['2'] as $keyG => $valueG) {
                if(trim(preg_replace('/\s+/','',strtolower($_iv['group']))) == trim(preg_replace('/\s+/','',strtolower($valueG['name'])))) {
                    $_iv['group_id'] = $valueG['id'];
                }
            }
            
            //-- Invert network name to id
            foreach($allinfo['3'] as $keyN => $valueN) {
                if(trim(preg_replace('/\s+/','',strtolower($_iv['network']))) == trim(preg_replace('/\s+/','',strtolower($valueN['name'])))) {
                    $_iv['network_id'] = $valueN['id'];
                }
            }
            
            //-- Invert agent name to id
            foreach($allinfo['1'] as $keyA => $valueA) {
                if(trim(preg_replace('/\s+/','',strtolower($_iv['agent']))) == trim(preg_replace('/\s+/','',strtolower($valueA['name'])))) {
                    $_iv['agent_id'] = $valueN['id'];
                }
            }
            $item = array(
                'phone' => $_iv['sim'],
                'modified' => $time,
                'delete_flag' => 0,
                'status' => 1,
                'list_city_id'  =>  '',
                'list_group_id' =>  '',
                'list_network_id'   =>  '',
                'price' =>  '',
                'price_update'  =>  ''
            );
            if($_iv['agent_id']) $item['list_city_id'] = $_iv['agent_id'];
            if($_iv['group_id']) $item['list_group_id'] = $_iv['group_id'];
            if($_iv['network_id']) $item['list_network_id'] = $_iv['network_id'];
            if($_iv['price']) {
                $item['price'] = $_iv['price'];
                $item['price_update'] = $_iv['price'];
            }
            array_push($simBatch, $item);
        }
        
        if(count($simBatch) != 0 && $this->sim_model->addSimBatch($simBatch)) {
            echo json_encode(array(
                'success'   =>  '1',
                'group'     => count($batchGroup),
                'network'   => count($batchNetwork),
                'agent'     => count($batchAgent),
                'sim'       => count($simBatch)
            ));
        } else {
            echo json_encode(array(
                'success'   =>  '0'
            ));
        }
        die();
        ///////End
        //--END
    }
    
    private function vbflush() {
        static $output_handler = null;
        if ($output_handler === null) {
            $output_handler = @ini_get('output_handler');
        }

        if ($output_handler == 'ob_gzhandler') {
            // forcing a flush with this is very bad
            return;
        }
        flush();
        if (function_exists('ob_flush') AND function_exists('ob_get_length') AND ob_get_length() !== false) {
            @ob_flush();
        } else if (function_exists('ob_end_flush') AND function_exists('ob_start') AND function_exists('ob_get_length') AND ob_get_length() !== FALSE) {
            @ob_end_flush();
            @ob_start();
        }
    }

}

?>
